#!/usr/bin/python
# -*- coding: utf-8 -*-
# --------------------------------------
# Author:  LJ
# Email:   admin@attacker.club
# Last Modified: 2018-06-19 21:33:43

# :output: 
# {
#     "data":[
#         {
#             "{#PNAME}":"named",
#             "{#PPORT}":"53"
#         },
#         {
#             "{#PNAME}":"mysqld",
#             "{#PPORT}":"3306"
#         }
#     ]
# }


import commands
import re

# 规定程序监听的端口，zabbix自动扫描
# 以后用cmdb 返回一个字典
APPS_LIST={
    'nginx:':[80,443,18118,9001],
    'php':[9000,80],
    'php-fpm':[9000],
    'node':[3008,4008,5071,7001,7002],
    'PM2':[4006],
    'java':[2181,6201,6202,6203,6204,6205,8201,8202,8203,8204,8205,8207,8208,9001,9101,18021,18022,19201],
    'mongodb':[27017,27000,27001],
    'redis-server':[6379,7000,7001],
    'mysqld':[3306],
    'mariadb':[3306],
    'named':[53],
    'rsync':[873],
    'openvpn':[1194],
    'slapd':[389],
    'python':[8000,9001,4505,4506],
    'sshd':[22,6022],
    'master':[25],
    'sendmail:':[25],
    'tnslsnr':[1521],
    }

##########获取系统服务名称和监听端口
# Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
# tcp        0      0 127.0.0.1:17000             0.0.0.0:*                   LISTEN      3597/redis-server 1 
# tcp        0      0 :::8009                     :::*                        LISTEN      15698/java          
def filterList():
    apps_str = "|".join(APPS_LIST.keys())
    # CMD="netstat -tnpl|grep -v ':::'|grep -E '%s'" % apps_list
    CMD="sudo netstat -tnpl" 
    tmpStr = commands.getoutput(CMD)
    tmpList = tmpStr.split("\n")
    newList = []
    for i in tmpList:
        if i.find('LISTEN') < 0:
            continue
        
        APP_PORT_REG = re.search(r"(127.0.0.1:|:::|0.0.0.0:)(\d+).+\d+/(\S+)",i)
        if APP_PORT_REG is not None:
            _APP_PORT = APP_PORT_REG.groups()
            APP_PORT = list(_APP_PORT[-2:])
            if APP_PORT[1] in APPS_LIST and APP_PORT[0]:
                port = int(APP_PORT[0])
                if port in APPS_LIST[APP_PORT[1]] and APP_PORT not in newList:
                    newList.append(APP_PORT)
    return newList
   
def main():
    import json
    netInfo = filterList()
    #格式化成适合zabbix lld的json数据
    ports = []
    for port,app in  netInfo: 
        ports += [{'{#PNAME}':app,'{#PPORT}':port}] 
    print json.dumps({'data':ports},sort_keys=True,indent=4,separators=(',',':'))


if __name__ == "__main__":
    main()
